package antidestiny.utilib.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.TextView;

import antidestiny.utilib.R;
import antidestiny.utilib.Aide;

/**
 * Created by Hero on 2017/1/1.
 */

public class TTFTextView extends TextView {
    public TTFTextView(Context context, AttributeSet attr) {
        super(context,attr);
        loadFont(context,attr);
    }

    public TTFTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        loadFont(context, attrs);
    }

    @android.support.annotation.RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public TTFTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        loadFont(context, attrs);
    }

    /**
     * 加载ttf字体
     *
     * @param context 环境
     * @param attrs   从这里获取信息
     */
    private void loadFont(Context context, @Nullable AttributeSet attrs) {
        if(isInEditMode())return;//便于预览

        if (attrs == null) return;
        TypedArray array=context.obtainStyledAttributes(attrs,R.styleable.icon_font);
        String fontAssetPath = array.getString(R.styleable.icon_font_ttf);
        array.recycle();

        if (fontAssetPath != null) {
            Typeface iconfont = Typeface.createFromAsset(context.getAssets(), fontAssetPath);
            if (iconfont == null) throw new RuntimeException("加载字体失败了。");
            setTypeface(iconfont);
        }else{
            Aide.t("未找到信息。");
        }
    }
}
